import { PageContainer } from '@ant-design/pro-components';
import { Conversation, Conversations, Sender } from '@ant-design/x';
import type { ConversationsProps } from '@ant-design/x';
import { history, request, useParams } from '@umijs/max';
import qs from 'qs';
import { useEffect, useState } from 'react';
import React from 'react';
import { UserOutlined, PlusOutlined, EditOutlined, DeleteOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Button, Col, Flex, Input, Row } from 'antd';
import { Bubble } from '@ant-design/x';
import Markdown from 'react-markdown';
import { GetProp } from 'antd';
// import remarkGrm from 'remark-gfm';
// import rehypeRaw from 'rehype-raw';

import { chatRoomList, chatRoomAdd, chatRoomUpdate, chatRoomDel } from '@/services/ant-design-pro/service';

const fooAvatar: React.CSSProperties = {
  color: '#f56a00',
  backgroundColor: '#fde3cf',
};

const barAvatar: React.CSSProperties = {
  color: '#fff',
  backgroundColor: '#87d068',
};

const hideAvatar: React.CSSProperties = {
  visibility: 'hidden',
};

export default() => {
    //获取浏览器路由参数
    const params = useParams();
    //const[data, setData] = useState<string>('');
    const[text, setText] = useState<string>('');
    const[loading, setLoading] = useState<boolean>(false);
    const[msgList, setMsgList] = useState<Record<string, any>[]>([]);
    const[conversations, setConversations] = useState<Conversation[]>([]);
    const[conversationKey, setConversationKey] = useState<string>('');

    useEffect(() => {
        // 获取用户所有的会话窗口（聊天室）
        chatRoomList({}).then(res => {
            console.log('聊天室列表：', res.data);
            setConversations(res.data.map((item: Record<string, any>) => ({
                ...item,
                key: item.roomId,
                rootId: item.roomId,
                label: item.roomName,
            })))
        }).catch(err => {
            console.log('err', err);
        })
    }, []);

    useEffect(() => {
        console.log('params:', params);
        // 根据获取会话记录
        request('http://localhost:8080/openapi/chat/history', {
            method: 'POST',
            headers: {
                "content-type": "application/x-www-form-urlencoded",
            },
            data: qs.stringify({
                sessionId: params.id,
            }),
        }).then(res =>{
            console.log(res);
            if (res.code === 200 && res.data.length > 0) {
                setMsgList(res.data.map((item: Record<string, any>) => {
                    const newItem = {
                        key: item.messageId,
                        placement: item.messageType === 'USER' ? 'end' : 'start',
                        content: item.content,
                    }
                    //console.log(newItem);
                    return newItem;
                }));
            } else {
                setMsgList([]);
            }
        }).catch(err => {
            console.log('err', err);
        });
    }, [params.id]); // 中括号内的元素，表示绑定那个模型

    const messageRender=(value: string) => {
        return <Markdown>{value}</Markdown>;
        // return (
        //     <Markdown
        //         rehypePlugins={[rehypeRaw]}
        //         remarkPlugins={[remarkGrm]}
        //         components={{
        //             think: ({node, ...props}) => <div className='think-box' />
        //         }}
        //     >
        //         {value}
        //     </Markdown>);
    }

    // 右侧对话头像
    const rolesObject: GetProp<typeof Bubble.List, 'roles'> = {
        ai: {
            placement: 'start',
            avatar: { icon: <UserOutlined />, style: { background: '#fde3cf' } },
            typing: { step: 5, interval: 20 },
            style: {
                maxWidth: window.innerWidth / 1.5,
            },
        },
        user: {
            placement: 'end',
            avatar: { icon: <UserOutlined />, style: { background: '#87d068' } },
        },
    };

    const handleRenameSubmit = (conversation: Conversation, newName: string) => {
        if (newName.trim() === '' || conversation.label === newName) {
            console.log('名称无效或未更改，不用接口提交...');
            setConversations(conversations.map(item => 
                item.key === conversation.key ? { ...item, editable: false } : item
            ));
            return
        }
        // 1. 发送更新请求
        chatRoomUpdate({
            roomId: conversation.key,
            roomName: newName,  // 使用用户输入的新名称
        }).then(res => {
            if (res.code === 200) {
                // 2. 更新本地状态
                setConversations(conversations.map(item => 
                item.key === conversation.key
                    ? { ...item, label: newName, editable: false }  // 更新名称并关闭编辑
                    : item
                ));
            } else {
                console.log(res);
            }
        }).catch(err => {
            console.error('重命名失败', err);
            // 3. 出错时恢复状态（保留原名称，仅关闭编辑）
            setConversations(conversations.map(item => 
                item.key === conversation.key ? { ...item, editable: false } : item
            ));
        });
    };

    // 左侧会话操作菜单
    const menuConfig: ConversationsProps['menu'] = (conversation) => {
        return {
            trigger: (menuInfo) => <EllipsisOutlined />,
            items: [
                {
                    label: '重命名',
                    key: 'rename',
                    icon: <EditOutlined />,
                },
                {
                    label: '删除',
                    key: 'remove',
                    icon: <DeleteOutlined  style={{color: '#ff1100'}}/>,
                    danger: true,
                }
            ],
            onClick: (menuInfo) => {
                menuInfo.domEvent.stopPropagation();
                if (menuInfo.key === 'remove') {
                    // 判断是否有roomId，有需要调用后端接口进行删除
                    let current = conversations.filter((item) => item.key === conversation.key);
                    if (current.length > 0) {
                        chatRoomDel({
                            roomId: current[0].roomId,
                        }).then(res => {
                            console.log(res);
                        }).catch(err => {
                            console.log('remove err', err);
                        })
                    }
                    setConversations(conversations.filter((item) => item.key !== conversation.key));
                } else if (menuInfo.key === 'rename') {
                    setConversations(
                        conversations.map((item) => ({
                            ...item,
                            editable: item.key === conversation.key,
                        })),
                    );
                }
            }
        }
    };

    return(
        <PageContainer title={false}>
            <Row gutter={16}>
                <Col span={6}>
                    <Button
                        block
                        type='primary'
                        icon={<PlusOutlined />}
                        onClick={() => {
                            const key = `${new Date().getTime()}`;
                            setConversations([
                                ...conversations,
                                {
                                    key: key,
                                    label: '新会话',
                                    editable: false,
                                }
                            ]);
                            if (!conversationKey) {
                                setConversationKey(key);
                            }
                        }}
                    >
                        新聊天
                    </Button>
                    <div style={{height: window.innerHeight - 200, overflowY: 'auto', marginTop: 5}}>
                        {conversations.length > 0 && (
                            <Conversations
                                onActiveChange={value => {
                                    const current = conversations.filter((item) => item.key === value);
                                    if (!current[0].roomId) {
                                        chatRoomAdd({
                                            roomName: '新聊天',
                                        }).then(res => {
                                            history.push(`/chat/${res.data}`);
                                            setConversationKey(res.data);
                                            setConversations(conversations.map(item => {
                                                if (item.key === res.data) {
                                                    item.key = res.data;
                                                    item.roomId = res.data;
                                                }
                                                return item;
                                            }))
                                        })
                                    } else {
                                        history.push(`/chat/${value}`);
                                        setConversationKey(value);
                                    }
                                }}
                                style={{padding: 0, marginTop: 16}}
                                menu={menuConfig}
                                activeKey={conversationKey}
                                // items={conversations}
                                items={conversations.map(conversation => ({
                                    ...conversation,
                                    // 添加自定义渲染逻辑
                                    label: conversation.editable ? (
                                    <div onClick={e => e.stopPropagation()}>
                                        <Input autoFocus size="small"
                                            defaultValue={typeof conversation.label === 'string' ? conversation.label : ''}
                                            onBlur={(e) => {
                                                //显示声明 e.target 为 HTMLInputElement 类型
                                                const target = e.target as HTMLInputElement;
                                                handleRenameSubmit(conversation, target.value);
                                                e.stopPropagation();
                                            }}
                                            onPressEnter={(e) => {
                                                //显示声明 e.target 为 HTMLInputElement 类型
                                                const target = e.target as HTMLInputElement;
                                                handleRenameSubmit(conversation, target.value);
                                                e.stopPropagation();
                                            }}
                                            onClick={e => e.stopPropagation()}
                                            style={{ width: '100%' }}
                                        />
                                    </div>
                                    ) : conversation.label
                                }))}
                            />
                        )}
                    </div>
                </Col>
                <Col span={18}>
                    <Flex gap="middle" vertical style={{marginBottom: 16}}>
                        {/* {
                            msgList.map((item, index) => (
                                <Bubble
                                    key={index}
                                    loading={item.loading}
                                    placement={item.placement}
                                    content={item.content}
                                    messageRender={messageRender}
                                    avatar={{ icon: <UserOutlined />, style: fooAvatar }}
                                />
                            ))
                        } */}
                        <Bubble.List
                            roles={rolesObject}
                            style={{ height: window.innerHeight -200}}
                            items={
                                msgList.map((item, index) => ({
                                    key: index,
                                    role: item.placement === 'end' ? 'user' : 'ai',
                                    content: messageRender(item.content),
                                    loading: !item.content
                                }
                            ))
                            }
                        />
                    </Flex>
                    <Sender disabled={loading} loading={loading} value={text}
                        onChange={value => {
                            setText(value);
                        }}
                        onSubmit={vlaue => {
                            console.log('输入内容：', vlaue);
                            setText('');
                            setLoading(true);
                            // 设置消息列表内容
                            setMsgList([
                                ...msgList,
                                // 用户消息
                                { placement: 'end', content: vlaue, },
                                // AI回复消息
                                { placement: 'start', content: '', loading: true, },
                            ]);
                            // 如何打印数组内容
                            // setMsgList(prev => {
                            //     const newList = [
                            //         ...prev,
                            //         // 用户消息
                            //         { placement: 'end', content: vlaue, },
                            //         // AI回复消息
                            //         { placement: 'start', content: '', loading: true, },
                            //     ];
                            //     console.log('新状态:', newList);
                            //     return newList;
                            // });
                            request('http://localhost:8080/openapi/chat/chat', {
                                method: 'POST',
                                headers: {
                                    "content-type": "application/x-www-form-urlencoded",
                                },
                                data: qs.stringify({
                                    sessionId: conversationKey,
                                    text: vlaue,
                                }),
                                responseType: 'stream',
                                onDownloadProgress: res => {
                                    //console.log('响应内容：', res);
                                    //setData(res.currentTarget.response);
                                    setMsgList(prevList => {
                                        // 创建新数组副本
                                        const newList = [...prevList];
                                        // 获取最后一个元素（出栈）
                                        const pop = newList.pop();
                                        // 更新AI回复消息
                                        const updatedMsg = {
                                            ...pop,
                                            content: res.currentTarget.response,
                                            loading: false
                                        };
                                        // 返回更新后的列表
                                        return [...newList, updatedMsg];
                                    });
                                }
                            }).then(result => {
                                //console.log('完整响应内容：', result);
                                //console.log('end');
                                setLoading(false);
                            }).catch(err => {
                                console.log('err', err);
                                setLoading(false);
                            })
                        }}
                    />
                </Col>
            </Row>
        </PageContainer>
    )
}
